/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package restaurante.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import restaurante.bancodados.CriaConexao;
import restaurante.logica.Refeicao;

/**
 *
 * @author Fernanda
 */
public class RefeicaoDao {
    private Connection conexao;

    public RefeicaoDao() throws SQLException{
        this.conexao = CriaConexao.getConexao();
    }

    public void adiciona(Refeicao p) throws SQLException{
        String  sql = "insert into refeicao (valor_total)" +
                "values (?)";
        PreparedStatement stmt = conexao.prepareStatement(sql);

        // Seta os valores
        stmt.setString(1, String.valueOf(p.getValor_total()));

        // Executa o código SQL
        stmt.execute();
        
        // Identificar qual é o último ID criado
        ResultSet lastId = stmt.getGeneratedKeys();
        lastId.next();
        p.setId(lastId.getInt(1));
        stmt.close();
        
        
    }

    public  List<Refeicao> getLista(String busca) throws SQLException{
        String sql = "Select * from refeicao where nome like ?";
        PreparedStatement stmt = this.conexao.prepareStatement(sql);

        stmt.setString(1, busca);       // inserção do caracter de busca.

        ResultSet rs = stmt.executeQuery();

        List<Refeicao> minhaLista = new ArrayList<Refeicao>();

        while(rs.next()){
            Refeicao p1 = new Refeicao();
            p1.setId(rs.getInt("id"));
            p1.setValor_total(Float.parseFloat(rs.getString("valor_total")));

            minhaLista.add(p1);
        }

        rs.close();
        stmt.close();
        return minhaLista;
    }


    public void altera(Refeicao r1) throws SQLException{
        String sql = "update refeicao set valor_total=? where id=?";
        PreparedStatement stmt = conexao.prepareStatement(sql);

        // Seta os valores

        stmt.setString(1, String.valueOf(r1.getValor_total()));
        stmt.setString(2, String.valueOf(r1.getId()));

        // Executa o código SQL
        stmt.execute();
        stmt.close();

    }

    public void remove(Refeicao p1) throws SQLException{
        String sql = "delete from refeicao where id=?";
        PreparedStatement stmt = conexao.prepareStatement(sql);

        stmt.setString(1, String.valueOf(p1.getId()));

        stmt.execute();
        stmt.close();

    }


}
